<template>
    <el-input v-model="page.question" style="width: 240px" placeholder="根据题干查询" />
    <el-tree-select placeholder="选择阶段" :props="defaultProps" v-model="page.subId" :data="levels"
        :render-after-expand="false" style="width: 240px;" />
    <el-select v-model="page.typeId" placeholder="选择题型" style="width: 240px">
        <el-option v-for="item in types" :label="item.typeName" :value="item.id" />
    </el-select>

    <el-button style="margin-left: 30px;" type="primary" icon="Search" @click="getData()">搜索</el-button>
    <el-button icon="Refresh" @click="resetQuery()">刷新</el-button>
    <el-button style="margin-left: 15px;" type="primary" icon="Download" @click="offQuest()">导出试题</el-button>
    <el-table @selection-change="handleSelectionChange" v-loading="loading" :data="tableData"
        style="width: 100%;height: 575px;" :stripe="true">
        <el-table-column label="试题编号" prop="id" width="110" />
        <el-table-column label="题型" width="120">
            <template #default="scope">
                <span v-if="scope.row.typeId == 1">单选题</span>
                <span v-if="scope.row.typeId == 2">多选题</span>
                <span v-if="scope.row.typeId == 3">判断题</span>
                <span v-if="scope.row.typeId == 4">简答题</span>
            </template>
        </el-table-column>
        <el-table-column label="题干" prop="question" width="280">
            <template #default="scope">
                <span class="answer-text">{{ scope.row.question.split("/")[0] }}</span>
            </template>
        </el-table-column>
        <el-table-column label="答案" width="350px">
            <template #default="scope">
                <span style="width: 300px;" class="answer-text">{{ scope.row.answerTxt }}</span>
            </template>
        </el-table-column>
        <el-table-column label="所属课程" prop="subjectName" width="120" />
        <el-table-column style="height: 30px;" label="状态" width="120">
            <template #default="scope">
                <el-tag v-if="scope.row.state == 0" type="success">正常</el-tag>
                <el-tag v-else type="danger">下线</el-tag>
            </template>
        </el-table-column>


        <el-table-column>
            <template #default="scope">

                <el-popover placement="top" trigger="hover" content="查看试题详情">
                    <template #reference>
                        <el-icon class="hoverColor" @click="edit(scope.row)">
                            <View />
                        </el-icon>
                    </template>
                </el-popover>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="page.pageNum" v-model:page-size="page.pageSize" :page-sizes="[1, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />

    <el-dialog v-model="editFlog" width="500">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon :rules="rules"
            label-width="auto" class="demo-ruleForm">

            <el-form-item label="试题类型: " prop="question">
                <el-select v-model="ruleForm.typeId" placeholder="选择题型" style="width: 240px">
                    <el-option v-for="item in type" :label="item.typeName" :value="item.id" :disabled="item.disabled" />
                </el-select>
            </el-form-item>
            <el-form-item label="题干: " prop="question">
                <el-input type="textarea" v-if="ruleForm.typeId > 2" placeholder="Please input"
                    v-model="ruleForm.question" />
                <div v-else>
                    <el-input type="textarea" placeholder="Please input" v-model="ruleForm.body" />
                    <el-input placeholder="Please input" v-model="ruleForm.a" />
                    <el-input placeholder="Please input" v-model="ruleForm.b" />
                    <el-input placeholder="Please input" v-model="ruleForm.c" />
                    <el-input placeholder="Please input" v-model="ruleForm.d" />
                </div>

            </el-form-item>
            <el-form-item label="答案: " prop="answerTxt">
                <el-input v-if="ruleForm.typeId == 4" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }"
                    v-model="ruleForm.answerTxt" />
                <el-radio-group v-if="ruleForm.typeId == 3" v-model="ruleForm.answerTxt" class="ml-4">
                    <el-radio value="正确" size="large" style="color:green">正确</el-radio>
                    <el-radio value="错误" size="large" style="color:red">错误</el-radio>
                </el-radio-group>
                <div v-if="ruleForm.typeId <= 2">
                    <el-select v-if="ruleForm.typeId != 2" v-model="ruleForm.answerTxt" placeholder="Select"
                        style="width: 240px">
                        <el-option v-for="item in abcd" :label="item.name" :value="item.value" />
                    </el-select>
                    <el-select v-else multiple v-model="ruleForm.sels" placeholder="Select" style="width: 240px">
                        <el-option v-for="item in abcd" :label="item.name" :value="item.value" />
                    </el-select>
                </div>
            </el-form-item>

            <el-form-item label="申请原因" prop="cause">
                <el-input v-model="ruleForm.cause" type="textarea" />
            </el-form-item>

            <div style="text-align: right;">
                <el-button type="primary" @click="upQuestion()">
                    提交申请
                </el-button>
            </div>
        </el-form>
    </el-dialog>
</template>
<script setup>
import { findAllQuestion, findAllType, findAllLevel, download, submitApplication } from '@/api/admin/questions.js';
import { ref, onMounted, watch,getCurrentInstance,reactive } from "vue";
import { ElMessage } from 'element-plus'
import { useUserStore1 } from '../../store/userStore.js'
const { proxy } = getCurrentInstance();
const defaultProps = {
    children: 'slearningProgress',
    label: 'levelName',
}
const editFlog = ref(false)
const loading = ref(false)
const ruleForm = ref({})
const tableData = ref([])
const levels = ref([])
const types = ref([])
const type = ref([])
const dels = ref([])
const abcd = ref([
    {
        name: "A",
        value: "A"
    },
    {
        name: "B",
        value: "B"
    },
    {
        name: "C",
        value: "C"
    },
    {
        name: "D",
        value: "D"
    },
])
const user = useUserStore1().userInfo;

const page = ref({
    typeId: null,
    pageNum: 1,
    pageSize: 10
})

const offQuest = () => {
    download(page.value).then(res => {
        const blob = new Blob([res.data], { type: 'application/octet-stream' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'example.docx';
        a.click();
        URL.revokeObjectURL(url);
    });
}

const handleSelectionChange = (val) => {
    dels.value = val
}

const getData = () => {
    loading.value = true
    findAllQuestion(page.value).then(res => {
        tableData.value = res.data.obj.list
        page.value.total = res.data.obj.total
        loading.value = false
    })
}
getData()


const resetQuery = () => {
    page.value = {
        typeId: null,
        pageNum: 1,
        pageSize: 10
    }
    getData()
}

const getLevel = () => {
    findAllLevel().then(res => {
        levels.value.push({
            levelName: "全部试题",
            value: null
        })
        res.data.obj.forEach(element1 => {
            element1.value = element1.id
            element1.slearningProgress.forEach(element2 => {
                element2.value = element2.id
                element2.levelName = element2.name
                element2.slearningProgress = element2.ssubjects
                element2.slearningProgress.forEach(element3 => {
                    element3.levelName = element3.subjectName
                    element3.value = element3.id
                });
            });
            levels.value.push(element1)
        });
    })
}
getLevel()


const getType = () => {
    findAllType().then(res => {
        types.value.push({ id: null, typeName: '全部题型' })
        res.data.obj.forEach(element => {
            types.value.push(element)
        });
        type.value = res.data.obj
    })
}
getType()

const edit = (row) => {
    ruleForm.value.cause = ''
    type.value[1] = { typeName: " 多选题", id: 2 }
    type.value[0] = { typeName: " 单选题", id: 1 }
    editFlog.value = true
    ruleForm.value = row
    if (ruleForm.value.answerTxt.length > 4) {
        type.value[1] = { typeName: " 多选题(答案长度过大 不能为多选题) 修改后请重新进入", id: 2, disabled: true }
    }
    if (ruleForm.value.answerTxt.length > 1) {
        type.value[0] = { typeName: " 单选题(答案长度过大 不能为单选题) 修改后请重新进入", id: 1, disabled: true }
    }
    ruleForm.value.sels = row.answerTxt.split('')
    ruleForm.value.body = ruleForm.value.question.split('/')[0]
    ruleForm.value.a = ruleForm.value.question.split('/')[1].split('_')[0]
    ruleForm.value.b = ruleForm.value.question.split('/')[1].split('_')[1]
    ruleForm.value.c = ruleForm.value.question.split('/')[1].split('_')[2]
    ruleForm.value.d = ruleForm.value.question.split('/')[1].split('_')[3]
}
const rules = reactive({
    cause: [{ required: true, message: '申请原因不能为空', trigger: 'blur' }],
})
const upQuestion = () => {
    proxy.$refs["ruleFormRef"].validate(valid => {
        if (valid) {
            if (ruleForm.value.typeId <= 2) {
                ruleForm.value.stem = ruleForm.value.body + "/" + ruleForm.value.a + "_" + ruleForm.value.b + "_" + ruleForm.value.c + "_" + ruleForm.value.d
                if (ruleForm.value.typeId == 2) {
                    var s = ""
                    ruleForm.value.sels.forEach(element => {
                        s += element
                    });
                    ruleForm.value.answerTxt = s
                }
            }
            ruleForm.value.userId = user.userId
            ruleForm.value.qid = ruleForm.value.id
            ruleForm.value.id = undefined
            ruleForm.value.answertxt = ruleForm.value.answerTxt
            submitApplication(ruleForm.value).then(res => {
                if (res.data.code == 200) {
                    getData()
                    editFlog.value = false
                    ElMessage.success("提交成功")
                } else {
                    editFlog.value = false
                    ElMessage.error(res.data.message)
                    getData()
                }
            })
        }
    })

}

const handleSizeChange = (val) => {
    page.pageSize = val
    getData()
}
const handleCurrentChange = (val) => {
    page.pageNum = val
    getData()
}

</script>
<style scoped>
.answer-text {
    white-space: nowrap;
    /* 防止文本换行 */
    overflow: hidden;
    /* 隐藏超出部分 */
    text-overflow: ellipsis;
    /* 显示省略号 */
    width: 100%;
    /* 或指定一个具体的宽度，如 150px，取决于你的列宽 */
    display: inline-block;
    /* 使得宽度和overflow属性生效 */
}

.hoverColor:hover {
    color: rgb(56, 97, 0);
    font-size: 24px;
}

.hoverColor {
    font-size: 22px;
}
</style>